package com.gulimall.search.service.imp;

import com.alibaba.fastjson.JSON;
import com.common.to.UpSkuTo;
import com.gulimall.search.config.GulimallElasticsearchConfig;
import com.gulimall.search.constant.SearchProductConstant;
import com.gulimall.search.service.EsProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class EsProductSaveServiceImp implements EsProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<UpSkuTo> upSkuToList) throws IOException {
        //保存到es
        //1.给es中建立索引
        BulkRequest bulkRequest=new BulkRequest();
        for (UpSkuTo upSkuTo : upSkuToList) {
            IndexRequest indexRequest=new IndexRequest(SearchProductConstant.PRODUCT_INDEX);
            indexRequest.id(upSkuTo.getSkuId().toString());
            String jsonString = JSON.toJSONString(upSkuTo);
            indexRequest.source(jsonString,XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //2.批量保存这些数据,普通的保存是调用index方法，批量保存调用的就是bulk
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        boolean hasFailures = bulkResponse.hasFailures();
        if(hasFailures){
            List<String> failIdList = Arrays.stream(bulkResponse.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("EsProductSaveServiceImp，es保存上架商品信息错误"+failIdList);
            return false;
        }
        return true;
    }
}
